#!/usr/bin/env coffee

import {mkdirSync,readFileSync,writeFileSync,existsSync} from 'fs'
import {HOME} from '../const/dir'
import {join,dirname} from 'path'
import { unpack, pack } from 'msgpackr'
import {types} from 'util'

export default new Proxy(
  {}
  get:(self,name)=>
    file = join(HOME,name)
    mkdirSync(
      dirname file
      recursive: true
    )
    (init)=>
      if existsSync(file)
        return unpack readFileSync(file)

      if init instanceof Function
        init = init()
        if types.isPromise init
          return init.then (r)=>
            writeFileSync file, pack(r)
            r
      writeFileSync file, pack(init)
      return init
)

